/** @jsxImportSource @emotion/react */
import * as React from "react";
import {InputLine, TextArea, Text, BlobInputList, Button, InputDatalist, useToast, SuffixInput, ColumnWidth, Input, LineColumn
} from "customize-easy-ui-component";
import {
    InspectRecordLayout, InternalItemProps, useInputControlSure, useItemInputControl
} from "../../common/base";
import {EditStorageContext} from "../../StorageContext";
import {Each_ZdSetting, useTableEditor} from "../../hook/useRepTableEditor";
import {useMeasureInpFilter} from "../../common/hooks";
import {useUppyUpload} from "../../hook/useUppyUpload";
import {useMedia} from "use-media";
import {assertNamesUnique} from "../../common/eHelper";
import {arraySetInp,} from "../../../common/tool";


const 示图说明选=['详见单线图。'];
const itemA测点位置=['示图说明','_FILE_S部位','检测结果'];
//只能上不变的：不能hook是死循环
const defaultValCb= (par: { 检测结果?: any; })=>{
    const { 检测结果 }=par||{};
    if(!检测结果)   par.检测结果='对图示1-18、55-71号焊缝外表面进行100%光谱分析，未见超标缺陷，检测结果为1级。';
    return  par;
}
export const ResultDiagram=
  React.forwardRef((
    { children, show ,alone=true,redId,nestMd, repId}:InternalItemProps,  ref
  ) => {
      const {modified,setModified,} =React.useContext(EditStorageContext) as any;
      const [getInpFilter] = useMeasureInpFilter(null, itemA测点位置, defaultValCb);
      const {inp, setInp,onSure} = useInputControlSure({ ref,redId,nestMd });
      const onFinish = React.useCallback(async(upfile: any, del:boolean) => {
          onSure({...inp, '_FILE_S部位': upfile});
          !modified && setModified(true);
      }, [inp, modified,onSure,setModified]);
      const [uploadDom]=useUppyUpload({ repId:repId!,
           maxFile:5, onFinish, storeObj: inp?._FILE_S部位
      });

    return (
      <InspectRecordLayout inp={inp} setInp={setInp}  getInpFilter={getInpFilter} show={show} redId={redId} nestMd={nestMd}
                           alone={alone}  label={'光谱分析结果，部位及缺陷示意图'}>
          <InputLine label='检测部位图：'>
              <BlobInputList value={inp?.示图说明 || ''} rows={5} datalist={示图说明选}
                             onListChange={v => setInp({...inp, 示图说明: v || undefined}) } />
          </InputLine>
          位置示意图：
          {uploadDom}
          检测结果:
        <TextArea  value={inp?.检测结果 ||''} rows={8}
                 onChange={e => setInp({ ...inp, 检测结果: e.currentTarget.value||undefined}) } />
        {children}
      </InspectRecordLayout>
    );
} );

const 部件名称选=['工艺管道' ];
const 仪器型号选=['PMI-MASTER Pro2' ];
const 取样方法选=['光谱' ];

/**原来的第一项：使用单位； ？？
 * */
export const config测量仪 = [
    [['使用单位', '_$使用单位'],  ['部件名称', {n:'部件',t:'l',l:部件名称选}]],
    [['仪器型号',{n:'仪器型',t:'l',l:仪器型号选}], ['仪器编号', '仪器编'] ],
    [['执行标准', '检标准'],  ['取样方法', {n:'取样',t:'l',l:取样方法选}]],
];

//【定做表格编辑器做法2】1，可不采用useTableEditor({editAs });来注入的； 单个回调注入也可以的。
//【优点】这个回调局部化，不需要知道表格名，以及表格的当前操作行号就能保存。 本方式的解耦合较好！存储字段名‘f’要对上。
const cb备注= (inp: any, setInp: React.Dispatch<React.SetStateAction<any>>,name:string) => {
   return  <InputDatalist value={(inp?.[name]) || ''} datalist={['Φ108弯头']}
                   onListChange={v => setInp({ ...inp, [name] :v || undefined}) } />
}
const cb标称材质= (inp: any, setInp: React.Dispatch<React.SetStateAction<any>>,name:string) => {
    return  <InputDatalist value={(inp?.[name]) || ''} datalist={['20']}
                           onListChange={v => setInp({ ...inp, [name] :v || undefined}) } />
}

export const config评定=[['编号','n',70],['材质','h',90,cb标称材质],   ] as Each_ZdSetting[];
const itemA评定=['评定表' ];
export const EvaluationForm=
    React.forwardRef(({ children, show ,alone=true,refWidth,redId,nestMd}:InternalItemProps,  ref
    ) => {
        const [getInpFilter]=useMeasureInpFilter(null,itemA评定,);
        const {inp, setInp} = useItemInputControl({ ref,redId,nestMd });
        const {storage, } =React.useContext(EditStorageContext) as any;
        //【纯动态】的：不能 config评定.push(['s色s','ce2',85]); 这样子 每一次render都会导致 config评定[] 数组加一次数据的。几个组件包含左边的报告页面都同步增加列数！
        const configNew =React.useMemo(()=>{
            const subStorage= '_SPECTR_VS_'+redId;
            const { [subStorage]: subObjAll }=storage;
            // console.log("元素及含量表,切花个个数=", inp?._YSN_, 'sdf1===', subObjAll,'redIAAAd=',subObjAll?._YSN_);
            let addings=new Array(Number(subObjAll?._YSN_)||1).fill(null).map(( _,  w:number) => {
                const title=subObjAll?.元素?.[w] || ('元素'+(w+1));
                return [title, ('e'+w), 55] as Each_ZdSetting;
            });
            return [...(config评定.slice(0,2)), ...addings, ...(config评定.slice(2))];
        },[config评定]);
        const tableName='评定表';
        const headview=<Text variant="h5">
            光谱分析-元素及含量表。
        </Text>;
        //不用默认Input，想用列表选择输入的： const editAs=(obj:any, setObj:React.Dispatch<React.SetStateAction<any>>, seq:number | null)=>{};
        const [render部位汇总]=useTableEditor({inp, setInp,  headview,
            config: configNew, table:tableName, column:4,  maxRf:3, });

        return (
            <InspectRecordLayout inp={inp} setInp={setInp}  getInpFilter={getInpFilter} show={show}  redId={redId} nestMd={nestMd}
                                 alone={alone}  label={'光谱分析-元素及含量表'}>
                {render部位汇总}
            </InspectRecordLayout>
        );
    } );


/**【开发测试用的】
 * */
export const EntranceSetup =
    React.forwardRef((
        {children, show, alone = true, repId, verId, rep}: InternalItemProps, ref
    ) => {
        const atPrint = useMedia('print');
        const toast = useToast();
        const checkName = true;      //开发测试完，改成=false, 测试时 REACT_APP_TEST 需设置， 开发模式的校对开关。
        const doCheckNames = React.useCallback((verId: string) => {
            //【承压更少项目】，那些属于公共模板目录的 分项报告的唯一性检查在对方自己检查看。
            const result = assertNamesUnique([{value: rep?.tzFields},
                {value: config测量仪, type:'esnt'},
                {value:[...itemA测点位置,...itemA评定, ...itemA元素集 ]},
                 ]);
            toast({title: "完成！", subtitle: result ? "没发现冲突" : "测试开关没开", intent: "success"});
        }, [rep,toast]);
        const getInpFilter = React.useCallback((par: any) => {}, []);
        const {inp, setInp} = useItemInputControl({ref});
        if (atPrint) return null;
        else return (
            <InspectRecordLayout inp={inp} setInp={setInp} getInpFilter={getInpFilter} show={show}
                                 alone={alone} label={'初始化本报告，默认值配置等'}>
                {checkName && <div>
                    <Text variant="h5">
                        构建开发模板时的工具：校验模板的存储name冲突；
                    </Text>
                    <Button intent='primary' onPress={() => {
                        doCheckNames(verId!);
                    }}>校验模板name唯一性</Button>
                </div>
                }
                <hr/>
            </InspectRecordLayout>
        );
    });


const itemA元素集=['单内编','_YSN_','元素','备注'];
export const ElementSet=
React.forwardRef((
    { children, show ,alone=true,redId,nestMd, repId}:InternalItemProps,  ref
) => {
    const [getInpFilter] = useMeasureInpFilter(null, itemA元素集, );
    const {inp, setInp,onSure} = useInputControlSure({ ref,redId,nestMd });
    return (
        <InspectRecordLayout inp={inp} setInp={setInp}  getInpFilter={getInpFilter} show={show} redId={redId} nestMd={nestMd}
                             alone={alone}  label={'光谱分析报告-目标元素设置'}>
            <LineColumn>
                {/*<InputLine label='单位内编号：'>*/}
                {/*    <BlobInputList value={inp?.单内编 || ''} rows={1} datalist={['见特性表']}*/}
                {/*                   onListChange={v => setInp({...inp, 单内编: v || undefined}) } />*/}
                {/*</InputLine>*/}
                <InputLine  label='目标元素？设计检测元素的个数：' >
                    <SuffixInput type="number"  value={inp?._YSN_ ||'1'} onSave={txt=> setInp({...inp,_YSN_: txt || undefined })}>个</SuffixInput>
                </InputLine>
            </LineColumn>
            而这{inp?._YSN_}个元素符号输入如下:
            <ColumnWidth clnWidth={100}>
            { (new Array(Number(inp?._YSN_)||1)).fill(null).map(( _,  w:number) => {
                return <InputLine  key={w} label={`元素${w+1}`}>
                        <Input  value={inp?.元素?.[w] ||''}
                                onChange={e => arraySetInp('元素',w,e.currentTarget.value||undefined,inp,setInp) } />
                    </InputLine>
            }) }
            </ColumnWidth>
            <br/>
            注意这些元素配置好了之后，再录入元素及含量表，若元素删除或修改的会导致元素及含量表的数据对不上。<br/>
            {children}
        </InspectRecordLayout>
    );
} );

